package client.service;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import client.io.ClientIO;
import domain.action.Action;
import domain.appointment.Appointment;
import domain.doctor.Doctor;
import domain.session.Request;
import domain.session.Response;

public class AppointmentService {

	public static void addAppointment(Appointment appt) {
		JSONObject requestJson = new JSONObject();
		requestJson.put("appointment", appt.getJSON());
		ClientIO.sendRequest(new Request(Action.ADD_APPOINTMENT, requestJson));
	}

	public static void remove(Appointment a) {
		JSONObject requestJson = new JSONObject();
		requestJson.put("appointment", a.getJSON());
		ClientIO.sendRequest(new Request(Action.REMOVE_APPOINTMENT, requestJson));
	}

	public static List<Appointment> getPatientAppointments(Integer userId) {
		JSONObject requestJson = new JSONObject();
		requestJson.put("userId", userId);
		ClientIO.sendRequest(new Request(Action.GET_PATIENT_APPOINTMENTS, requestJson));

		return getAppointmentsFromResponse(ClientIO.getResponse());
	}

	public static List<Appointment> getDoctorAppointments(Integer userId) {
		JSONObject requestJson = new JSONObject();
		requestJson.put("userId", userId);
		ClientIO.sendRequest(new Request(Action.GET_DOCTOR_APPOINTMENTS, requestJson));

		return getAppointmentsFromResponse(ClientIO.getResponse());
	}

	public static List<Appointment> getLastMonthDoctorAppointments(
			Integer doctorId) {
		JSONObject requestJson = new JSONObject();
		requestJson.put("userId", doctorId);
		ClientIO.sendRequest(new Request(Action.GET_LAST_MONTH_DOCTOR_APPOINTMENTS, requestJson));

		return getAppointmentsFromResponse(ClientIO.getResponse());
	}

	public static List<Appointment> getFutureDoctorAppointments(Integer userId) {
		JSONObject requestJson = new JSONObject();
		requestJson.put("userId", userId);
		ClientIO.sendRequest(new Request(Action.GET_FUTURE_DOCTOR_APPOINTMENTS, requestJson));

		return getAppointmentsFromResponse(ClientIO.getResponse());
	}

	public static List<Appointment> getFuturePatientAppointments(Integer userId) {
		JSONObject requestJson = new JSONObject();
		requestJson.put("userId", userId);
		ClientIO.sendRequest(new Request(Action.GET_FUTURE_PATIENT_APPOINTMENTS, requestJson));

		return getAppointmentsFromResponse(ClientIO.getResponse());
	}

	public static void save() {
		JSONObject requestJson = new JSONObject();
		ClientIO.sendRequest(new Request(Action.SAVE_APPOINTMENT, requestJson));
	}
	
	private static List<Appointment> getAppointmentsFromResponse(final Response response) {
		JSONObject responseJson = response.getResponse();
		JSONArray apptArray = responseJson.getJSONArray("appointments");
		
		List<Appointment> appts = new ArrayList<Appointment>();
		
		for (int i = 0; i < apptArray.length(); i++) {
			appts.add(new Appointment(apptArray.getJSONObject(i)));
		}
		
		return appts;
	}

}
